<template>
  <div class="restart-history">
    <!-- 只读提示 -->
    <div class="readonly-notice">
      <el-icon><InfoFilled /></el-icon>
      <span>此表为只读，仅供查看重启历史记录</span>
    </div>

    <!-- 搜索卡片 -->
    <div class="search-section">
      <el-card shadow="hover" class="search-card">
        <template #header>
          <div class="search-header">
            <div class="search-title">
              <el-icon><Search /></el-icon>
              <span>搜索与筛选</span>
            </div>
          </div>
        </template>
        
        <el-form :model="searchForm" class="search-form">
          <div class="search-form-content">
            <div class="search-form-fields">
              <el-form-item label="节点名称">
                <el-input v-model="searchForm.node_name" placeholder="模糊搜索" clearable style="width: 160px" />
              </el-form-item>
              
              <el-form-item label="组件类型">
                <el-select v-model="searchForm.component" placeholder="全部" clearable style="width: 120px">
                  <el-option label="全部" value="" />
                  <el-option label="FE" value="fe" />
                  <el-option label="BE" value="be" />
                </el-select>
              </el-form-item>
              
              <el-form-item label="集群标识">
                <el-select v-model="searchForm.cluster_tag" placeholder="全部" clearable style="width: 140px">
                  <el-option label="全部" value="" />
                  <el-option
                    v-for="tag in clusterTags"
                    :key="tag"
                    :label="tag"
                    :value="tag"
                  />
                </el-select>
              </el-form-item>
              
              <el-form-item label="重启结果">
                <el-select v-model="searchForm.restart_result" placeholder="全部" clearable style="width: 120px">
                  <el-option label="全部" value="" />
                  <el-option label="成功" value="success" />
                  <el-option label="失败" value="failure" />
                  <el-option label="超时" value="timeout" />
                </el-select>
              </el-form-item>
              
              <el-form-item label="状态">
                <el-select v-model="searchForm.status" placeholder="全部" clearable style="width: 140px">
                  <el-option label="全部" value="" />
                  <el-option label="活跃" value="active" />
                  <el-option label="已解决" value="resolved" />
                  <el-option label="达到最大次数" value="max_attempts" />
                </el-select>
              </el-form-item>
            </div>
            
            <div class="search-form-actions">
              <el-button 
                type="info" 
                @click="advancedSearchExpanded = !advancedSearchExpanded" 
                class="advanced-btn"
                plain
              >
                <el-icon>
                  <component :is="advancedSearchExpanded ? 'ArrowUp' : 'ArrowDown'" />
                </el-icon>
                高级筛选
              </el-button>
              <el-button type="primary" @click="handleSearch" class="search-btn">
                <el-icon><Search /></el-icon>
                搜索
              </el-button>
              <el-button type="warning" @click="handleReset" class="reset-btn">
                <el-icon><Refresh /></el-icon>
                重置
              </el-button>
            </div>
          </div>
          
          <!-- 高级筛选折叠区域 -->
          <transition name="advanced-filter">
            <div v-show="advancedSearchExpanded" class="advanced-filter-section">
              <div class="advanced-filter-fields">
                <el-form-item label="时间范围">
                  <el-date-picker
                    v-model="dateRange"
                    type="datetimerange"
                    range-separator="至"
                    start-placeholder="开始时间"
                    end-placeholder="结束时间"
                    value-format="YYYY-MM-DD HH:mm:ss"
                    style="width: 380px"
                  />
                </el-form-item>
              </div>
            </div>
          </transition>
        </el-form>
      </el-card>
    </div>

    <!-- 表格卡片 -->
    <div class="table-section">
      <el-card shadow="hover" class="table-card">
        <template #header>
          <div class="table-header">
            <div class="table-title">
              <el-icon><List /></el-icon>
              <span>重启历史</span>
            </div>
            <div class="table-header-actions">
              <el-button type="success" @click="handleRefresh" class="refresh-btn" :loading="loading" size="small">
                <el-icon><Refresh /></el-icon>
                刷新
              </el-button>
              <div class="table-info">
                <div class="pagination-control-wrapper clickable" @click="togglePagination">
                  <span class="page-count">本页 {{ historyList.length }} 条</span>
                  <div class="divider"></div>
                  <span class="pagination-info">
                    {{ currentPage }}/{{ Math.ceil(total / pageSize) || 1 }}
                  </span>
                  <el-icon class="pagination-toggle-icon">
                    <ArrowUp v-if="paginationVisible" />
                    <ArrowDown v-else />
                  </el-icon>
                </div>
              </div>
            </div>
          </div>
        </template>
        <div class="table-container">
          <el-table
            :data="historyList"
            v-loading="loading"
            class="enhanced-table"
            style="width: 100%"
            :height="600"
            table-layout="fixed"
            :stripe="false"
            :border="false"
          >
            <el-table-column prop="node_name" label="节点名称" width="140" fixed="left" show-overflow-tooltip />
            
            <el-table-column prop="component" label="组件类型" width="100">
              <template #default="{ row }">
                <el-tag :type="row.component === 'fe' ? 'primary' : 'success'" size="small">
                  {{ row.component.toUpperCase() }}
                </el-tag>
              </template>
            </el-table-column>
            
            <el-table-column prop="cluster_tag" label="集群标识" width="120">
              <template #default="{ row }">
                <el-tag type="info" size="small">{{ row.cluster_tag }}</el-tag>
              </template>
            </el-table-column>
            
            <el-table-column prop="restart_result" label="重启结果" width="100">
              <template #default="{ row }">
                <el-tag :type="getRestartResultType(row.restart_result)" size="small">
                  {{ getRestartResultText(row.restart_result) }}
                </el-tag>
              </template>
            </el-table-column>
            
            <el-table-column prop="start_time" label="开始时间" width="180" />
            
            <el-table-column prop="end_time" label="结束时间" width="180" />
            
            <el-table-column prop="duration_seconds" label="持续时间" width="120">
              <template #default="{ row }">
                {{ formatDuration(row.duration_seconds) }}
              </template>
            </el-table-column>
            
            <el-table-column prop="status" label="状态" width="120">
              <template #default="{ row }">
                <el-tag :type="getStatusType(row.status)" size="small">
                  {{ getStatusText(row.status) }}
                </el-tag>
              </template>
            </el-table-column>
            
            <el-table-column prop="total_attempts" label="总尝试" width="100" align="center" />
            
            <el-table-column prop="successful_restarts" label="成功次数" width="100" align="center" />
            
            <el-table-column prop="error_message" label="错误信息" width="300" show-overflow-tooltip />
            
            <el-table-column label="操作" width="80" fixed="right">
              <template #default="{ row }">
                <div class="action-buttons">
                  <el-tooltip content="查看详情" placement="top">
                    <el-button type="primary" size="small" @click="handleViewDetail(row)" circle>
                      <el-icon><View /></el-icon>
                    </el-button>
                  </el-tooltip>
                </div>
              </template>
            </el-table-column>
          </el-table>
        </div>
        
        <!-- 分页折叠区域 -->
        <transition name="pagination-slide">
          <div v-show="paginationVisible" class="pagination-section">
            <el-pagination
              v-model:current-page="currentPage"
              v-model:page-size="pageSize"
              :total="total"
              :page-sizes="[10, 20, 50, 100]"
              layout="total, sizes, prev, pager, next, jumper"
              @size-change="handleSizeChange"
              @current-change="handlePageChange"
              background
            />
          </div>
        </transition>
      </el-card>
    </div>

    <!-- 详情对话框 -->
    <RestartDetailDialog
      v-model="detailDialogVisible"
      :detail="currentDetail"
    />
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed } from 'vue'
import { ElMessage } from 'element-plus'
import {
  Search, Refresh, InfoFilled, View, ArrowUp, ArrowDown
} from '@element-plus/icons-vue'
import RestartDetailDialog from './RestartDetailDialog.vue'
import api from '@/utils/api'
import { createLogger } from '@/utils/logger'

const componentLogger = createLogger('RestartHistory')

const loading = ref(false)
const historyList = ref([])
const clusterTags = ref([])
const currentPage = ref(1)
const pageSize = ref(20)
const total = ref(0)
const paginationVisible = ref(false)
const dateRange = ref([])
const advancedSearchExpanded = ref(false)

const searchForm = reactive({
  node_name: '',
  component: '',
  cluster_tag: '',
  restart_result: '',
  status: ''
})

const detailDialogVisible = ref(false)
const currentDetail = ref(null)

// 重启结果映射
const restartResultMap = {
  'success': { text: '成功', type: 'success' },
  'failure': { text: '失败', type: 'danger' },
  'timeout': { text: '超时', type: 'warning' }
}

const getRestartResultText = (result) => {
  return restartResultMap[result]?.text || result
}

const getRestartResultType = (result) => {
  return restartResultMap[result]?.type || 'info'
}

// 状态映射
const statusMap = {
  'active': { text: '活跃', type: 'warning' },
  'resolved': { text: '已解决', type: 'success' },
  'max_attempts': { text: '达到最大次数', type: 'danger' }
}

const getStatusText = (status) => {
  return statusMap[status]?.text || status
}

const getStatusType = (status) => {
  return statusMap[status]?.type || 'info'
}

// 格式化持续时间
const formatDuration = (seconds) => {
  if (!seconds || seconds < 0) return '-'
  const minutes = Math.floor(seconds / 60)
  const secs = seconds % 60
  if (minutes > 0) {
    return `${minutes}分${secs}秒`
  }
  return `${secs}秒`
}

// 获取重启历史列表
const fetchData = async () => {
  loading.value = true
  try {
    const params = {
      page: currentPage.value,
      size: pageSize.value,
      ...searchForm
    }
    
    // 处理时间范围
    if (dateRange.value && dateRange.value.length === 2) {
      params.start_time = dateRange.value[0]
      params.end_time = dateRange.value[1]
    }
    
    // 过滤空值
    Object.keys(params).forEach(key => {
      if (params[key] === '' || params[key] === null) {
        delete params[key]
      }
    })
    
    const response = await api.get('/starrocks-cluster-monitor/restart-history', { params })
    if (response.data.success) {
      historyList.value = response.data.data.rows
      total.value = response.data.data.total
      
      // 提取集群标识列表
      const tags = new Set(historyList.value.map(item => item.cluster_tag))
      clusterTags.value = Array.from(tags)
      
      componentLogger.info('重启历史加载成功', { total: total.value })
    }
  } catch (error) {
    componentLogger.error('加载重启历史失败', error)
    ElMessage.error('加载重启历史失败')
  } finally {
    loading.value = false
  }
}

const handleSearch = () => {
  currentPage.value = 1
  fetchData()
}

const handleReset = () => {
  Object.keys(searchForm).forEach(key => {
    searchForm[key] = ''
  })
  dateRange.value = []
  currentPage.value = 1
  fetchData()
}

const handleRefresh = () => {
  fetchData()
  ElMessage.success('刷新成功')
}

const togglePagination = () => {
  paginationVisible.value = !paginationVisible.value
}

const handleViewDetail = (row) => {
  currentDetail.value = { ...row }
  detailDialogVisible.value = true
}

const handleSizeChange = () => {
  currentPage.value = 1
  fetchData()
}

const handlePageChange = () => {
  fetchData()
}

onMounted(() => {
  fetchData()
})

defineExpose({
  fetchData
})
</script>

<style scoped>
.restart-history {
  margin-top: 20px;
}

.readonly-notice {
  background: #f0f9ff;
  border: 1px solid #bfdbfe;
  border-radius: 6px;
  padding: 12px 16px;
  margin-bottom: 16px;
  color: #1e40af;
  display: flex;
  align-items: center;
  gap: 8px;
  font-size: 14px;
}

.search-section {
  margin-bottom: 20px;
}

.search-card {
  border-radius: 8px;
}

.search-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.search-title {
  display: flex;
  align-items: center;
  gap: 8px;
  font-size: 16px;
  font-weight: 600;
  color: #303133;
}

.search-title .el-icon {
  color: #409eff;
}

.search-form-content {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  gap: 20px;
}

.search-form-fields {
  flex: 1;
  display: flex;
  flex-wrap: wrap;
  gap: 16px;
}

.search-form-fields .el-form-item {
  margin-bottom: 0;
}

.search-form-actions {
  display: flex;
  gap: 12px;
  flex-shrink: 0;
}

.table-container {
  min-height: 600px;
}

.enhanced-table {
  font-family: 'Inter', 'PingFang SC', 'Microsoft YaHei', sans-serif;
  border-radius: 16px;
  overflow: hidden;
  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.08);
}

.table-container .el-table {
  width: 100% !important;
  border-radius: 16px;
  overflow: hidden;
  background: #fff;
}

.table-container .el-table__header {
  background: #f8f9fa;
  border-bottom: 1px solid #e4e7ed;
}

.table-container .el-table th {
  background: transparent !important;
  border: none !important;
  padding: 16px 12px !important;
  font-weight: 500 !important;
  color: #606266 !important;
  font-size: 14px !important;
}

.enhanced-table .el-table__header-wrapper th {
  font-size: 14px !important;
  font-weight: 500 !important;
  color: #606266 !important;
  white-space: nowrap !important;
}

.enhanced-table :deep(.el-table__header-wrapper) th .cell {
  white-space: nowrap !important;
  overflow: visible !important;
  display: flex !important;
  align-items: center !important;
  flex-wrap: nowrap !important;
}

/* 排序图标容器不换行 */
.enhanced-table :deep(.el-table__header-wrapper) th .caret-wrapper {
  flex-shrink: 0 !important;
  margin-left: 4px !important;
}

/* 表格内容字体大小统一 */
.enhanced-table .el-table__body-wrapper td {
  font-size: 14px !important;
}

.table-container .el-table td {
  border-bottom: 1px solid rgba(0, 0, 0, 0.05);
  padding: 12px;
  font-size: 14px;
  font-weight: 400;
  transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
  position: relative;
}

/* 分页区域 */
.pagination-section {
  padding: 16px;
  border-top: 1px solid #f0f0f0;
  background: #fafafa;
}

.pagination-section .el-pagination {
  display: flex;
  justify-content: center;
}

/* 分页折叠动画 */
.pagination-slide-enter-active,
.pagination-slide-leave-active {
  transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
}

.pagination-slide-enter-from,
.pagination-slide-leave-to {
  opacity: 0;
  max-height: 0;
  overflow: hidden;
}

.pagination-slide-enter-to,
.pagination-slide-leave-from {
  opacity: 1;
  max-height: 200px;
}

.enhanced-pagination {
  background: rgba(255, 255, 255, 0.8);
  backdrop-filter: blur(10px);
  border-radius: 12px;
  padding: 16px 24px;
  box-shadow: 
    0 8px 32px rgba(0, 0, 0, 0.08),
    0 2px 8px rgba(0, 0, 0, 0.04),
    inset 0 1px 0 rgba(255, 255, 255, 0.9);
  border: 1px solid rgba(255, 255, 255, 0.2);
  transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
}

.enhanced-pagination:hover {
  transform: translateY(-2px);
  box-shadow: 
    0 12px 40px rgba(0, 0, 0, 0.12),
    0 4px 16px rgba(0, 0, 0, 0.06),
    inset 0 1px 0 rgba(255, 255, 255, 0.95);
}

.enhanced-pagination .el-pagination__total {
  color: #4a5568;
  font-weight: 600;
  font-size: 14px;
  letter-spacing: 0.5px;
}

.enhanced-pagination .el-pagination__sizes .el-select .el-input__inner {
  border-radius: 8px;
  border: 1px solid rgba(220, 223, 230, 0.8);
  background: rgba(255, 255, 255, 0.9);
  transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
  font-weight: 500;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.02);
}

.enhanced-pagination .el-pagination__sizes .el-select .el-input__inner:hover {
  border-color: rgba(64, 158, 255, 0.6);
  background: #fff;
  transform: translateY(-1px);
  box-shadow: 0 4px 12px rgba(64, 158, 255, 0.1);
}

.enhanced-pagination .el-pagination__sizes .el-select .el-input__inner:focus {
  border-color: #409eff;
  background: #fff;
  box-shadow: 
    0 0 0 3px rgba(64, 158, 255, 0.1),
    0 4px 12px rgba(64, 158, 255, 0.15);
}

.enhanced-pagination .btn-prev,
.enhanced-pagination .btn-next {
  border-radius: 8px;
  border: 1px solid rgba(220, 223, 230, 0.8);
  background: linear-gradient(135deg, #fff 0%, #fafbfc 100%);
  transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
  font-weight: 600;
  color: #4a5568;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.02);
  min-width: 40px;
  height: 40px;
}

.enhanced-pagination .btn-prev:hover,
.enhanced-pagination .btn-next:hover {
  background: linear-gradient(135deg, #409eff 0%, #66b3ff 100%);
  border-color: transparent;
  color: white;
  transform: translateY(-2px);
  box-shadow: 
    0 8px 25px rgba(64, 158, 255, 0.25),
    0 3px 10px rgba(64, 158, 255, 0.15);
}

.enhanced-pagination .btn-prev:active,
.enhanced-pagination .btn-next:active {
  transform: translateY(0);
  box-shadow: 0 4px 12px rgba(64, 158, 255, 0.2);
}

.enhanced-pagination .el-pager li {
  border-radius: 8px;
  border: 1px solid rgba(220, 223, 230, 0.8);
  background: linear-gradient(135deg, #fff 0%, #fafbfc 100%);
  transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
  font-weight: 600;
  margin: 0 3px;
  min-width: 40px;
  height: 40px;
  color: #4a5568;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.02);
}

.enhanced-pagination .el-pager li:hover {
  background: linear-gradient(135deg, #f0f7ff 0%, #e6f3ff 100%);
  border-color: rgba(64, 158, 255, 0.3);
  color: #409eff;
  transform: translateY(-2px);
  box-shadow: 0 6px 20px rgba(64, 158, 255, 0.15);
}

.enhanced-pagination .el-pager li.is-active {
  background: linear-gradient(135deg, #409eff 0%, #66b3ff 100%);
  border-color: transparent;
  color: white;
  box-shadow: 
    0 8px 25px rgba(64, 158, 255, 0.3),
    0 3px 10px rgba(64, 158, 255, 0.2);
  transform: translateY(-1px);
}

.enhanced-pagination .el-pager li:active {
  transform: translateY(0);
}

.enhanced-pagination .el-pagination__jump {
  color: #4a5568;
  font-weight: 600;
}

.enhanced-pagination .el-pagination__jump .el-input__inner {
  border-radius: 8px;
  border: 1px solid rgba(220, 223, 230, 0.8);
  background: rgba(255, 255, 255, 0.9);
  transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
  font-weight: 500;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.02);
  height: 40px;
}

.enhanced-pagination .el-pagination__jump .el-input__inner:hover {
  border-color: rgba(64, 158, 255, 0.6);
  background: #fff;
  transform: translateY(-1px);
  box-shadow: 0 4px 12px rgba(64, 158, 255, 0.1);
}

.enhanced-pagination .el-pagination__jump .el-input__inner:focus {
  border-color: #409eff;
  background: #fff;
  box-shadow: 
    0 0 0 3px rgba(64, 158, 255, 0.1),
    0 4px 12px rgba(64, 158, 255, 0.15);
}

/* 表格头部样式 */
.table-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.table-title {
  display: flex;
  align-items: center;
  gap: 8px;
  font-size: 16px;
  font-weight: 600;
  color: #303133;
}

.table-title .el-icon {
  color: #409eff;
}

.table-header-actions {
  display: flex;
  align-items: center;
  gap: 12px;
}

.table-info {
  display: flex;
  align-items: center;
  gap: 8px;
}

.refresh-btn {
  border-radius: 6px;
  font-weight: 500;
}

.page-count {
  color: #606266;
  font-size: 14px;
  font-weight: 500;
}

.divider {
  width: 1px;
  height: 16px;
  background: #e4e7ed;
  margin: 0 8px;
}

.table-header-actions {
  display: flex;
  gap: 12px;
  align-items: center;
}

.table-info {
  display: flex;
  align-items: center;
}

.refresh-btn {
  background: linear-gradient(135deg, #67C23A 0%, #85CE61 100%);
  border: none;
  border-radius: 8px;
  color: #fff;
  box-shadow: 0 4px 12px rgba(103, 194, 58, 0.3);
  transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
  font-weight: 500;
}

.refresh-btn:hover {
  background: linear-gradient(135deg, #85CE61 0%, #67C23A 100%);
  box-shadow: 0 6px 20px rgba(103, 194, 58, 0.4);
  transform: translateY(-2px);
  color: #fff;
}

.pagination-control-wrapper {
  display: flex;
  align-items: center;
  gap: 8px;
  padding: 4px 8px;
  background: rgba(64, 158, 255, 0.08);
  border: 1px solid rgba(64, 158, 255, 0.2);
  border-radius: 4px;
  cursor: pointer;
  transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
  user-select: none;
  font-size: 12px;
  height: 24px;
}

.pagination-control-wrapper:hover {
  background: rgba(64, 158, 255, 0.12);
  border-color: rgba(64, 158, 255, 0.3);
  transform: translateY(-1px);
  box-shadow: 0 2px 8px rgba(64, 158, 255, 0.15);
}

.page-count {
  font-size: 12px;
  font-weight: 500;
  color: #909399;
  line-height: 1;
}

.divider {
  width: 1px;
  height: 12px;
  background: rgba(64, 158, 255, 0.3);
  margin: 0 2px;
}

.pagination-info {
  font-size: 12px;
  font-weight: 500;
  color: #409eff;
  letter-spacing: 0.5px;
  min-width: 24px;
  text-align: center;
  line-height: 1;
}

.pagination-toggle-icon {
  font-size: 12px;
  color: #409eff;
  transition: transform 0.3s cubic-bezier(0.4, 0, 0.2, 1);
}

/* 高级筛选样式 */
.advanced-filter-section {
  margin-top: 16px;
  padding-top: 16px;
  border-top: 1px solid #e4e7ed;
}

.advanced-filter-fields {
  display: flex;
  align-items: center;
  gap: 16px;
  flex-wrap: wrap;
}

.advanced-filter-fields .el-form-item {
  margin-bottom: 0;
}

/* 高级筛选折叠动画 */
.advanced-filter-enter-active,
.advanced-filter-leave-active {
  transition: all 0.3s ease;
  max-height: 200px;
  overflow: hidden;
}

.advanced-filter-enter-from,
.advanced-filter-leave-to {
  opacity: 0;
  max-height: 0;
  margin-top: 0;
  padding-top: 0;
}

.advanced-filter-enter-to,
.advanced-filter-leave-from {
  opacity: 1;
  max-height: 200px;
  margin-top: 16px;
  padding-top: 16px;
}

/* 操作按钮样式 */
.action-buttons {
  display: flex;
  gap: 8px;
  justify-content: center;
}

.action-buttons .el-button {
  width: 32px;
  height: 32px;
  padding: 0;
}
</style>

